package gx.web.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.databind.ObjectMapper;

import gx.entity.NewsType;
import gx.service.NewsTypeService;

@Controller
@RequestMapping("/mng/news_cate")
public class NewsTypeController {
	@Autowired
	private NewsTypeService newsTypeService;
	// 根据ID修改
		@RequestMapping("/list.jhtml")
		public ModelAndView list() throws Exception {
			System.out.println("news---------------------------------------------------------------");
			
			ModelAndView mav = new ModelAndView("/mng/news_cate/list");
			List<NewsType> list = newsTypeService.findAll();
			System.out.println(list.size());
			mav.addObject("list", list);
			return mav;
		}

		// 新增
		@RequestMapping("/add.jhtml")
		public String add(NewsType newsType) {
			newsTypeService.save(newsType);
			return "redirect:/mng/news_cate/list.jhtml";
		}

		// 根据ID查询详情
		@RequestMapping("/detail.jhtml")
		public ModelAndView detail(Integer id) throws Exception {
			ModelAndView mav = new ModelAndView("/mng/news_cate/detail");
			NewsType newsType = newsTypeService.get(id);
			mav.addObject("newsType", newsType);
			return mav;
		}

		// 根据ID修改
		@RequestMapping("/edit.jhtml")
		public String edit(Integer id, String type, String summary) {
			NewsType newsType  = newsTypeService.get(id);
			newsType.setType(type);
			newsType.setSummary(summary);
			newsTypeService.update(newsType);
			return "redirect:/mng/news_cate/list.jhtml";
		}

//		// 删除
//		@RequestMapping("/delete.jhtml")
//		public String delete(Integer id) {
//			newsTypeService.delete(id);
//			System.out.println(id + "--------------------");
//			return "redirect:/mng/news_cate/list.jhtml";
//		}

		// 模糊查询
		@RequestMapping("/search.jhtml")
		public ModelAndView Search(String condition) throws Exception {
			ModelAndView mav = new ModelAndView("mng/news_cate/list");// ?
			List<NewsType> list = newsTypeService.findByName(condition);
			mav.addObject("list", list);
			return mav;
		}
		//ajax删除
		@RequestMapping(value="/ajaxdelete.jhtml",produces="application/json;charset=UTF-8")
		@ResponseBody
		    public String ajaxdelete(Integer id)throws Exception{
			String rs="";
			try{
				newsTypeService.delete(id);
				rs="删除成功！";
			}catch(Exception e){
				rs="该新闻类型已在新闻列表中使用！";
			}
			ObjectMapper mapper=new ObjectMapper();
			String json=mapper.writeValueAsString(rs);
			return json;
		}
}
